package service

import (
	"context"
	"errors"
	"gitee.com/Frank098/devops-app-mgt/model"
	"gitee.com/Frank098/devops-app-mgt/utils"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"time"
)

var Namespace namespace

type namespace struct{}

func (n *namespace) GetNamespaceInfo(namespaceName string) (namespace *corev1.Namespace, err error) {
	namespace, err = K8s.ClientSet.CoreV1().Namespaces().Get(context.TODO(), namespaceName, metav1.GetOptions{})
	if err != nil {
		return nil, errors.New("获取Namespace详情失败, " + err.Error())
	}
	return namespace, nil
}

func (n *namespace) GetAllNamespace() (namespace []*model.GetNameSpaceInfo, err error) {
	namespaceList, err := K8s.ClientSet.CoreV1().Namespaces().List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		return nil, errors.New("获取Namespace列表失败, " + err.Error())
	}
	for _, namespaceListInfo := range namespaceList.Items {
		currentContainerTime := namespaceListInfo.CreationTimestamp
		dateOfDifference := utils.SubDays(time.Now(), currentContainerTime.Time)
		namespaceInfo := &model.GetNameSpaceInfo{
			Status: string(namespaceListInfo.Status.Phase),
			Name:   namespaceListInfo.Name,
			Age:    dateOfDifference,
		}
		namespace = append(namespace, namespaceInfo)
	}
	return namespace, nil
}

func (n *namespace) DeleteNamespace(namespaceName string) (err error) {
	err = K8s.ClientSet.CoreV1().Namespaces().Delete(context.TODO(), namespaceName, metav1.DeleteOptions{})
	if err != nil {
		return errors.New("删除Namespace失败, " + err.Error())
	}
	return nil
}

func (n *namespace) CreateNamespace(data *model.CreateNamespace) (err error) {
	namespaceClient := K8s.ClientSet.CoreV1().Namespaces()
	namespace := &corev1.Namespace{
		ObjectMeta: metav1.ObjectMeta{
			Name: data.Name,
		},
	}
	_, err = namespaceClient.Create(context.TODO(), namespace, metav1.CreateOptions{})
	if err != nil {
		return errors.New("创建Namespace失败, " + err.Error())
	}

	associated := K8s.ClientSet.CoreV1().ResourceQuotas(data.Name)
	Resources := &corev1.ResourceQuota{
		ObjectMeta: metav1.ObjectMeta{
			Name: data.Name,
		},
		Spec: corev1.ResourceQuotaSpec{
			Hard: map[corev1.ResourceName]resource.Quantity{
				corev1.ResourceLimitsCPU:      resource.MustParse(data.LimitsCpu),
				corev1.ResourceLimitsMemory:   resource.MustParse(data.LimitsMemory),
				corev1.ResourceRequestsCPU:    resource.MustParse(data.RequestsCpu),
				corev1.ResourceRequestsMemory: resource.MustParse(data.RequestsMemory),
			},
		},
	}
	_, err = associated.Create(context.TODO(), Resources, metav1.CreateOptions{})
	if err != nil {
		return errors.New("关联Namespace资源配置失败, " + err.Error())
	}
	return nil
}
